package com.bw.zhanggm.file.controller;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.zhanggm.file.config.AjaxResult;
import com.bw.zhanggm.file.entity.User;
import com.bw.zhanggm.file.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-01-12
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;


    @GetMapping
    public List<User> getList(){
        List<User> list = iUserService.list();
        return list;
    }


    @GetMapping("getUserInfoById")
    public User getUserInfoById(Integer id) {
        return iUserService.getById(id);
    }


    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        User userInfo = iUserService.getOne(lambdaQueryWrapper);
        if (userInfo == null) {
            return AjaxResult.error("用户名或密码错误");
        }

        if (!user.getPassword().equals(userInfo.getPassword())) {
            return AjaxResult.error("用户名或密码错误");
        }
        //生成token
        Map<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("id", user.getId());
        userInfoMap.put("username", user.getUsername());
        userInfoMap.put("role", user.getRole());
        String token = JWTUtil.createToken(userInfoMap, "123".getBytes());
        System.out.println(123);
        return AjaxResult.success("登录成功",token);
    }

}
